﻿using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace Security
{
    public class CipherText
    {
        public string Encrypt(string message)
        {
            using (var symm = SymmetricAlgorithm.Create())
            using (var mem = new MemoryStream())
            using (var writer = new CryptoStream(mem, symm.CreateEncryptor(), CryptoStreamMode.Write))
            {
                mem.WriteByte((byte)symm.Key.Length);
                mem.Write(symm.Key, 0, symm.Key.Length);
                mem.WriteByte((byte)symm.IV.Length);
                mem.Write(symm.IV, 0, symm.IV.Length);

                var buf = Encoding.UTF8.GetBytes(message);
                writer.Write(buf, 0, buf.Length);
                writer.FlushFinalBlock();
                return Convert.ToBase64String(mem.ToArray());
            }
        }

        public string Decrypt(string message)
        {
            using (var symm = SymmetricAlgorithm.Create())
            {
                var bytes = Convert.FromBase64String(message);
                var index = 0;
                var keyLength = bytes[index++];
                var key = bytes.Skip(index).Take(keyLength).ToArray();
                index += keyLength;

                var ivLength = bytes[index++];
                var iv = bytes.Skip(index).Take(ivLength).ToArray();
                index += ivLength;

                using (var mem = new MemoryStream(bytes.Skip(index).ToArray()))
                using (var reader = new CryptoStream(mem, symm.CreateDecryptor(key, iv), CryptoStreamMode.Read))
                using (var stream = new StreamReader(reader))
                {
                    return stream.ReadToEnd();
                }
            }
        }
    }
}
